package com.bsb.biz.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bsb.base.common.config.Const;
import com.bsb.base.common.config.Title;
import com.bsb.base.common.util.FileUtil;
import com.bsb.base.common.util.SmsUtil;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.common.util.UmengPushUtil;
import com.bsb.base.model.BsbApplyExpert;
import com.bsb.base.model.BsbApplyExpertExample;
import com.bsb.base.model.BsbUser;
import com.bsb.biz.service.BsbApplyExpertService;
import com.bsb.biz.service.BsbUserService;

import push.AndroidNotification;
import push.android.AndroidCustomizedcast;
import push.ios.IOSCustomizedcast;

@Controller
@RequestMapping("/bsbApplyExpert")
public class BsbApplyExpertController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbApplyExpert/list.do";
	
	@Resource
	private BsbApplyExpertService bsbApplyExpertService;
	@Resource
	private BsbUserService bsbUserService;
	
	@RequiresPermissions("bsbApplyExpert:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbApplyExpertExample bsbApplyExpertExample = new BsbApplyExpertExample();
		int totalCount = bsbApplyExpertService.countBsbApplyExpert(bsbApplyExpertExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbApplyExpertExample.setPageIndex((pageNum - 1) * pageSize);
		bsbApplyExpertExample.setPageSize(pageSize);
		bsbApplyExpertExample.setOrderByClause(" createDate DESC");
		List<BsbApplyExpert> bsbApplyExperts = bsbApplyExpertService.getPageBsbApplyExpert(bsbApplyExpertExample);
		for (BsbApplyExpert bsbApplyExpert : bsbApplyExperts) {
			String duty = bsbApplyExpert.getDuty();
			if(StringUtils.isNotEmpty(duty)){
				bsbApplyExpert.setDuty(Title.getNames(duty));
			}
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("bsbApplyExperts", bsbApplyExperts);
		return "/BsbApplyExpert/list";
	}
	
	@RequiresPermissions("bsbApplyExpert:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "/BsbApplyExpert/add";
	}

	@RequiresPermissions("bsbApplyExpert:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model, @ModelAttribute("bsbApplyExpert") BsbApplyExpert bsbApplyExpert) {
		bsbApplyExpertService.addBsbApplyExpert(bsbApplyExpert);
		return redirect;
	}
	
	@RequiresPermissions("bsbApplyExpert:delete")
	@RequestMapping(value = "/{uuid}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("uuid") String uuid) {
		bsbApplyExpertService.delBsbApplyExpertByUuid(uuid);
		return redirect;
	}
	
	@RequiresPermissions("bsbApplyExpert:update")
	@RequestMapping(value = "/{uuid}/update", method = RequestMethod.GET)
	public String toEdit(Model model,
			@PathVariable("uuid") String uuid) {
		BsbApplyExpert bsbApplyExpert = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		model.addAttribute("bsbApplyExpert", bsbApplyExpert);
		return "/BsbApplyExpert/edit";
	}
	
	@RequiresPermissions("bsbApplyExpert:check")
	@RequestMapping(value = "/{uuid}/check", method = RequestMethod.GET)
	public String check(Model model,
			@PathVariable("uuid") String uuid) {
		BsbApplyExpert bsbApplyExpert = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		String duty = bsbApplyExpert.getDuty();
		if(StringUtils.isNotEmpty(duty)){
			String names = Title.getNames(duty);
			bsbApplyExpert.setDuty(names);
		}
		String credImg = bsbApplyExpert.getCredImg();
		List<String> imgs = new ArrayList<String>();
		if(StringUtils.isEmpty(credImg)){
			imgs = Collections.emptyList();
		}else{
			if(credImg.contains(",")){
				String[] split = credImg.split(",");
				imgs = Arrays.asList(split);
			}else{
				imgs.add(credImg);
			}
		}
		model.addAttribute("imgs", imgs);
		model.addAttribute("bsbApplyExpert", bsbApplyExpert);
		return "/BsbApplyExpert/check";
	}
	
	/**
	 * 审核通过
	 * @param model
	 * @param uuid
	 * @return
	 */
	@RequiresPermissions("bsbApplyExpert:check")
	@RequestMapping(value = "/{uuid}/pass", method = RequestMethod.GET)
	@ResponseBody
	public Object pass(Model model,
			@PathVariable("uuid") String uuid,
			String skill,String profile) {
		BsbApplyExpert bsbApplyExpert = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == bsbApplyExpert){
			map.put("status", false);
			map.put("msg", "参数错误");
			return map;
		}
		String status = bsbApplyExpert.getStatus();
		if(!"0".equals(status)){
			map.put("status", false);
			map.put("msg", "此申请已被处理，不能再次审核");
			return map;
		}
		BsbApplyExpert expert = new BsbApplyExpert();
		if(StringUtils.isNotEmpty(skill)){
			expert.setSkill(skill);
		}
		if(StringUtils.isNotEmpty(profile)){
			expert.setSkill(profile);
		}
		expert.setUuid(uuid);
		expert.setStatus("1");
		expert.setUpdateBy((String)SecurityUtils.getSubject().getPrincipal());
		expert.setUpdateDate(new Date());
		try {
			bsbApplyExpertService.updatePass(expert);
			map.put("status", true);
			map.put("msg", "审核成功");
			
			String text = "恭喜您，您的专家申请已通过，请重新登录。";
			String userId = bsbApplyExpert.getUserId();
			String type = "13";
			Map<String,String> m = new HashMap<String,String>();
			m.put("type", type);
			try {
				UmengPushUtil.sendAndroidCustomizedcast(text, userId, m);
				UmengPushUtil.sendIOSCustomizedcast(text, userId, m);
			} catch (Exception e) {
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙");
			return map;
		}
	}
	/**
	 * 审核通过发送短信
	 * @param model
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/{uuid}/notify", method = RequestMethod.GET)
	@ResponseBody
	public Object notify(Model model,@PathVariable("uuid") String uuid){
		BsbApplyExpert bsbApplyExpertByUuid = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == bsbApplyExpertByUuid){
			map.put("status", false);
			map.put("msg", "参数错误");
			return map;
		}
		String userId = bsbApplyExpertByUuid.getUserId();
		if(StringUtils.isEmpty(userId)){
			map.put("status", false);
			map.put("msg", "参数错误用户id为空");
			return map;
		}
		BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userId);
		if(null == bsbUserByUuid){
			map.put("status", false);
			map.put("msg", "参数错误用户不存在");
			return map;
		}
		String phone = bsbUserByUuid.getPhone();
		String sendSms = SmsUtil.sendSms("8aaf07086006f38b01600bb5ea41012c", "238204", phone, null);
		map.put("status", true);
		map.put("msg", sendSms);
		return map;
	}
	/**
	 * 审核不通过
	 * @param model
	 * @param uuid
	 * @return
	 */
	@RequiresPermissions("bsbApplyExpert:check")
	@RequestMapping(value = "/{uuid}/nopass", method = RequestMethod.GET)
	@ResponseBody
	public Object nopass(Model model,String reason,
			@PathVariable("uuid") String uuid) {
		BsbApplyExpert bsbApplyExpert = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == bsbApplyExpert){
			map.put("status", false);
			map.put("msg", "参数错误");
			return map;
		}
		String status = bsbApplyExpert.getStatus();
		if(!"0".equals(status)){
			map.put("status", false);
			map.put("msg", "此申请已被处理，不能再次审核");
			return map;
		}
		if(StringUtils.isEmpty(reason)){
			map.put("status", false);
			map.put("msg", "不通过理由不能为空");
			return map;
		}
		BsbApplyExpert apply = new BsbApplyExpert();
		apply.setUuid(uuid);
		apply.setReason(reason);
		apply.setStatus("2");
		apply.setUpdateBy((String)SecurityUtils.getSubject().getPrincipal());
		try {
			bsbApplyExpertService.updateBsbApplyExpert(apply);;
			map.put("status", true);
			map.put("msg", "审核成功");
			
			String text = "很抱歉，您的申请未通过，请查看。";
			String userId = bsbApplyExpert.getUserId();
			String type = "12";
			Map<String,String> m = new HashMap<String,String>();
			m.put("type", type);
			m.put("uuid", uuid);
			
			try {
				UmengPushUtil.sendAndroidCustomizedcast(text, userId, m);
				UmengPushUtil.sendIOSCustomizedcast(text, userId, m);
			} catch (Exception e) {
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙");
			return map;
		}
	}
	
	/**
	 * 审核不通过发送短信
	 * @param model
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/{uuid}/refuse", method = RequestMethod.GET)
	@ResponseBody
	public Object refuse(Model model,@PathVariable("uuid") String uuid,String reason){
		BsbApplyExpert bsbApplyExpertByUuid = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == bsbApplyExpertByUuid){
			map.put("status", false);
			map.put("msg", "参数错误");
			return map;
		}
		String userId = bsbApplyExpertByUuid.getUserId();
		if(StringUtils.isEmpty(userId)){
			map.put("status", false);
			map.put("msg", "参数错误用户id为空");
			return map;
		}
		BsbUser bsbUserByUuid = bsbUserService.getBsbUserByUuid(userId);
		if(null == bsbUserByUuid){
			map.put("status", false);
			map.put("msg", "参数错误用户不存在");
			return map;
		}
		String phone = bsbUserByUuid.getPhone();
		String sendSms = SmsUtil.sendSms("8aaf07086006f38b01600bb5ea41012c", "238205", phone, new String[]{reason});
		map.put("status", true);
		map.put("msg", sendSms);
		return map;
	}
	/**
	 * 下载简历
	 * @param uuid
	 * @param response
	 * @param request
	 */
	@RequestMapping(value="/downresume/{uuid}",method=RequestMethod.GET)
	public void downresume(@PathVariable(value = "uuid") String uuid, HttpServletResponse response,
			HttpServletRequest request) {
		if (StringUtils.isEmpty(uuid)) {
			return;
		}
		BsbApplyExpert bsbApplyExpertByUuid = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		if(null == bsbApplyExpertByUuid){
			return;
		}
		String formerFile = bsbApplyExpertByUuid.getFormerFile();
		String realFile = bsbApplyExpertByUuid.getRealFile();
		int indexOf = realFile.indexOf("_");
		if (indexOf < 0) {
			return;
		}
		String substring = realFile.substring(indexOf + 1);
		realFile = Const.getDocBasePath() + substring + "/" + realFile;
		FileUtil.downloadFile(request, response, realFile, formerFile);
	}
	
	@RequiresPermissions("bsbApplyExpert:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model, @ModelAttribute("bsbApplyExpert") BsbApplyExpert bsbApplyExpert) {
		bsbApplyExpertService.updateBsbApplyExpert(bsbApplyExpert);
		return redirect;
	}
	
	@RequiresPermissions("bsbApplyExpert:view")
	@RequestMapping(value = "/{uuid}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("uuid") String uuid) {
		BsbApplyExpert bsbApplyExpert = bsbApplyExpertService.getBsbApplyExpertByUuid(uuid);
		model.addAttribute("bsbApplyExpert", bsbApplyExpert);
		return "/BsbApplyExpert/view";
	}
}
